<template>
  <a-modal
    v-model:visible="visible"
    title="确认需求"
    :confirmLoading="submitting"
    :width="560"
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-form layout="vertical">
      <a-form-item label="产品类别" required>
        <a-select
          v-model:value="selectedTypeId"
          placeholder="请选择产品类别"
          :options="productTypeOptions"
          :loading="loadingTypes"
          show-search
          :filter-option="(input, option) => (option?.label || '').toLowerCase().includes(input.toLowerCase())"
          @change="onTypeChange"
        />
      </a-form-item>

      <a-form-item label="产品名称" required>
        <a-select
          v-model:value="selectedProductIds"
          mode="multiple"
          placeholder="请选择产品名称（可多选）"
          :options="productNameOptions"
          :loading="loadingNames"
          :disabled="!selectedTypeId"
          show-search
          :filter-option="(input, option) => (option?.label || '').toLowerCase().includes(input.toLowerCase())"
          :max-tag-count="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue';
import axios from 'axios';
import { useUserStore } from '/@/store/modules/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { assignBusinessDeptUser, saveOrUpdate } from '../CustomersPool.api';

const { createMessage } = useMessage();
const userStore = useUserStore();

const visible = ref(false);
const submitting = ref(false);
const currentRecord = ref<any>(null);

const loadingTypes = ref(false);
const loadingNames = ref(false);
const productTypeOptions = ref<Array<{ label: string; value: string }>>([]);
const productNameOptions = ref<Array<{ label: string; value: string }>>([]);

const selectedTypeId = ref<string | undefined>(undefined);
const selectedTypeName = ref<string>('');
const selectedProductIds = ref<string[]>([]);
const selectedProductNames = ref<string[]>([]);

async function open(record: any) {
  currentRecord.value = record;
  selectedTypeId.value = undefined;
  selectedTypeName.value = '';
  selectedProductIds.value = [];
  selectedProductNames.value = [];
  productNameOptions.value = [];
  visible.value = true;
  await loadProductTypes();
}

async function loadProductTypes() {
  loadingTypes.value = true;
  try {
    const res = await axios.get('/jeecg-boot/products/productType/getProductTypeNameAndId', {
      headers: { 'X-Access-Token': userStore.getToken },
    });
    const list = Array.isArray(res.data) ? res.data : res.data?.result || [];
    productTypeOptions.value = list
      .filter((it: any) => it && it.id && it.productType)
      .map((it: any) => ({ value: it.id, label: it.productType }));
  } catch (e) {
    productTypeOptions.value = [];
  } finally {
    loadingTypes.value = false;
  }
}

async function onTypeChange(val: string, option: any) {
  selectedTypeId.value = val;
  selectedTypeName.value = option?.label || '';
  selectedProductIds.value = [];
  selectedProductNames.value = [];
  await loadProductNames(val);
}

async function loadProductNames(productTypeId: string) {
  if (!productTypeId) {
    productNameOptions.value = [];
    return;
  }
  loadingNames.value = true;
  try {
    const res = await axios.get('/jeecg-boot/products/productType/getProductNameByProductTypeId', {
      params: { productTypeId },
      headers: { 'X-Access-Token': userStore.getToken },
    });
    const list = Array.isArray(res.data) ? res.data : res.data?.result || [];
    productNameOptions.value = list
      .filter((it: any) => it && (it.id || it.productName))
      .map((it: any) => ({ value: it.id || it.productName, label: it.productName || it.name }));
  } catch (e) {
    productNameOptions.value = [];
  } finally {
    loadingNames.value = false;
  }
}

async function handleOk() {
  if (!currentRecord.value?.id) {
    createMessage.warning('缺少客户信息');
    return;
  }
  if (!selectedTypeId.value) {
    createMessage.warning('请选择产品类别');
    return;
  }
  if (!selectedProductIds.value.length) {
    createMessage.warning('请选择产品名称');
    return;
  }
  submitting.value = true;
  try {
    // 取产品名称文本
    selectedProductNames.value = productNameOptions.value
      .filter((opt) => selectedProductIds.value.includes(opt.value as string))
      .map((opt) => String(opt.label));

    // 1) 指定需求确认人员
    const currentUserId = userStore.getUserInfo?.id;
    const assignParams = { id: currentRecord.value.id, userId: currentUserId, developRole: '需求确认人员' };
    const assignRes = await assignBusinessDeptUser(assignParams);
    if (!assignRes || assignRes.success !== true) {
      createMessage.error(assignRes?.message || '需求确认失败');
      submitting.value = false;
      return;
    }

    // 2) 更新客户产品信息
    const updatePayload: any = {
      id: currentRecord.value.id,
      productType: selectedTypeName.value,
      productNameStr: selectedProductNames.value.join(','),
    };
    const updateRes = await saveOrUpdate(updatePayload, true);
    if (!updateRes || updateRes.success !== true) {
      createMessage.error(updateRes?.message || '更新产品信息失败');
      submitting.value = false;
      return;
    }

    createMessage.success('确认需求并保存产品信息成功');
    visible.value = false;
    emitAfterOk();
  } catch (e: any) {
    createMessage.error(e?.message || '操作失败');
  } finally {
    submitting.value = false;
  }
}

function handleCancel() {
  if (submitting.value) return;
  visible.value = false;
}

// 对外：让父组件可在成功后刷新
const afterOkHandlers: Array<() => void> = [];
function onAfterOk(handler: () => void) {
  afterOkHandlers.push(handler);
}
function emitAfterOk() {
  afterOkHandlers.forEach((h) => {
    try { h(); } catch {}
  });
}

defineExpose({ open, onAfterOk });
</script>

<style scoped>
</style>


